package com.cooper.mediadb;

import java.util.ArrayList;
import java.util.List;

import com.cooper.mediadb.SearchActionBarLayout.OnSearchBackListener;
import com.cooper.scrapemedialib.R;
import com.cooper.scraper.show.AdapterDataChangedListener;
import com.cooper.scraper.show.FanartAdapter;
import com.cooper.scraper.show.FanartViewStrategy;
import com.cooper.scraper.show.FanartsShow;
import com.cooper.scraper.show.FlowGalleryViewShow;
import com.cooper.scraper.show.ResourceCommandAction;
import com.cooper.scraper.show.ResourceShowListener;
import com.cooper.scraper.show.TileGalleryViewShow;
import com.cooper.slidingmenu.utils.SampleDialogBaseFragment;
import com.cooper.slidingmenu.utils.SingleFragmentContain;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

public abstract class MediaBrowseBaseFragment<T extends Media> extends
		SampleDialogBaseFragment implements AdapterDataChangedListener,
		ResourceShowListener<T>, OnSearchBackListener {

	private static class FanartsViewShowFactory {

		public static <T extends Media> FanartsShow<T> getFanartsViewShow(
				Activity activity, FanartViewStrategy<T> fanartViewStrategy,
				int height) {
			if (PreferenceManager.getDefaultSharedPreferences(activity)
					.getBoolean("perfernce_tile_fanart", false)) {
				return new TileGalleryViewShow<T>(
						activity.getApplicationContext(), fanartViewStrategy,
						activity.getWindowManager().getDefaultDisplay()
								.getWidth(), height, Media.HEIGHT_WIDHT_SCALE,
						R.drawable.missing);

			} else {
				return new FlowGalleryViewShow<T>(
						activity.getApplicationContext(), fanartViewStrategy,
						activity.getWindowManager().getDefaultDisplay()
								.getWidth(), height, Media.HEIGHT_WIDHT_SCALE,
						R.drawable.missing);
			}
		}
	}

	// public static final int AD_VIEW_HEIGHT = 76;
	private static final int GALLERY_HEIGHT = 440; // pix

	private RelativeLayout mainLayout;

	private View noResultMessage;
	private View rightWait;

	//private View searchEditView;

	private ImageButton navButton;

	private boolean tileGallery;

	protected String searchKeyword = null;

	public MediaBrowseBaseFragment() {
		super();
		setRetainInstance(true);
	}

	protected FanartsShow<T> fanartsViewShow = null;

	protected T currentMedia;
	private Integer switchSavePos = null;

	public T getCurrentMedia() {
		return currentMedia;
	}

	// public boolean onKeyBack() {
	// if (navButton)
	// }

	protected void switchMediaViewShow() {
		if (fanartsViewShow != null) {
			if ((tileGallery && fanartsViewShow instanceof TileGalleryViewShow)
					|| (!tileGallery && fanartsViewShow instanceof FlowGalleryViewShow))
				return;
			fanartsViewShow.removeFrom(mainLayout);
			fanartsViewShow.destroy();
		}

		fanartsViewShow = FanartsViewShowFactory.getFanartsViewShow(
				getActivity(), getViewStrategy(), getGalleryViewHeight());

		switchMediaViewAdapter();
		fanartsViewShow.registerContextMenu(this);
		fanartsViewShow.setCommands(commands);
		fanartsViewShow.showTo(mainLayout);
		fanartsViewShow.setMediasShowListener(this);

	}

	protected void switchMediaViewAdapter() {

		boolean curAdapterisSearch = searchKeyword != null;
		FanartAdapter<T> adapter = getFanartAdapter(curAdapterisSearch);

		if (curAdapterisSearch) {
			adapter.setSearchKeyword(searchKeyword);
		}

		boolean needRefresh = (curAdapterisSearch || (fanartsViewShow
				.getAdapter() == null));
		if (fanartsViewShow.getAdapter() == null
				|| !fanartsViewShow.getAdapter().equals(adapter)) {
			adapter.setDataChangedListener(this);
			if (fanartsViewShow.getAdapter() != null && curAdapterisSearch) {
				switchSavePos = fanartsViewShow.getSelectedPosition();
			}
			fanartsViewShow.setAdapter(adapter);
		}
		if (needRefresh) {
			fanartsViewShow.getAdapter().refresh();
		} else if (switchSavePos != null) {
			fanartsViewShow.setSelection(switchSavePos, false);
			switchSavePos = null;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("MediaBrowseBaseFragment", "Fragment call onCreate:" + this);
		setRetainInstance(true);
		initCommandAction();
		tileGallery = PreferenceManager.getDefaultSharedPreferences(
				getActivity()).getBoolean("perfernce_tile_fanart", false);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.d("MediaBrowseBaseFragment", "Fragment call onCreateView:" + this);
		View result = inflater.inflate(getContentView(), container, false);
		findView(result);
		return result;
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		Log.d("MediaBrowseBaseFragment", "Fragment call onDestroyView:" + this);
		if (fanartsViewShow != null) {
			fanartsViewShow.destroy();
			fanartsViewShow = null;
		}
	}

	@Override
	public void dataWaiting() {
		if (noResultMessage != null)
			noResultMessage.setVisibility(View.GONE);
		if (rightWait != null) {
			rightWait.setVisibility(View.VISIBLE);
		}

	}

	@Override
	public void dataComplete() {
		if (rightWait != null) {
			rightWait.setVisibility(View.GONE);
		}
		// WaitNextDataListener.DIRECTION_DOWN
	}

	@Override
	public void noResultData() {
		if (noResultMessage != null)
			noResultMessage.setVisibility(View.VISIBLE);
	}

	protected List<ResourceCommandAction<T>> commands;

	protected void initCommandAction() {
		commands = new ArrayList<ResourceCommandAction<T>>();
		ResourceCommandAction<T> actionCommand = new ResourceCommandAction<T>() {
			@Override
			public void execute(T media) {
				playMedia(media);
			}
		};
		actionCommand.setGroup(0);
		actionCommand.setIconResId(R.drawable.ic_play);
		actionCommand.setTitle(getResources().getString(
				R.string.media_menu_play));
		commands.add(actionCommand);

		actionCommand = new ResourceCommandAction<T>() {
			@Override
			public void execute(T media) {
				showMediaDetails(media);
			}
		};
		actionCommand.setGroup(0);
		actionCommand.setIconResId(R.drawable.ic_details);
		actionCommand.setTitle(getResources().getString(
				R.string.media_menu_info));
		commands.add(actionCommand);

	}

	protected void findView(View view) {
		mainLayout = (RelativeLayout) view.findViewById(R.id.main_layout);

		noResultMessage = view.findViewById(R.id.no_result_movie);
		rightWait = view.findViewById(R.id.right_waiting);

		navButton = (ImageButton) view.findViewById(R.id.nav_button);

		navButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				((SingleFragmentContain) getActivity()).showNavigation();
			}
		});

		View customActionBar = view.findViewById(R.id.customActionBar);
		if (customActionBar != null)
			((SearchActionBarLayout) customActionBar)
					.setOnSearchBackListener(this);


	}
	
	@Override
	public void onSearch(String keyword){
		searchKeyword = keyword;
		switchMediaViewAdapter();
	}

	@Override
	public void onSearchBack() {
		searchKeyword = null;
		switchMediaViewAdapter();
	}

	protected void showContinuePlayMediaDialog() {
		new ContinuePlayMediaDialog().show(getActivity()
				.getSupportFragmentManager(), "CONTINUE_PLAY_DIALOG");
	}

	protected void playMedia(List<Uri> uris, String title, Uri uri, int position) {
		((MediaMainActivity) getActivity()).playMedia(uris, title, uri,
				position);
	}

	protected void playMedia(List<Uri> uris, String title) {
		((MediaMainActivity) getActivity()).playMedia(uris, title);
	}

	protected int getGalleryViewHeight() {
		int screenHeight = getActivity().getWindowManager().getDefaultDisplay()
				.getHeight();
		int maxHeight = screenHeight
				- (int) getResources().getDimensionPixelSize(
						R.dimen.custombar_height);

		return Math.min(GALLERY_HEIGHT, maxHeight);
	}
	
	protected abstract void showMediaDetails(T media);

	protected abstract void onMediaPlayResult(Uri uri, int position);

	protected abstract FanartViewStrategy<T> getViewStrategy();

	protected abstract void onSelectPlayMedia(boolean continued);

	protected abstract void playMedia(T media);

	protected abstract int getContentView();

	protected abstract FanartAdapter<T> getFanartAdapter(boolean isSearch);
	
	public static class ContinuePlayMediaDialog extends DialogFragment
			implements DialogInterface.OnClickListener {

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			return new AlertDialog.Builder(getActivity()).setItems(
					R.array.continue_paly_media_select, this).create();
		}

		@Override
		public void onClick(DialogInterface dialog, int which) {
			((MediaMainActivity) getActivity()).getCurMediaControlFragment()
					.onSelectPlayMedia(which == 0);

		}


	}
}
